package main

import (
	"github.com/pkg/errors"
	"io"
	"myCloud/dbmodel"
	"myCloud/exif"
	"os"
	"path/filepath"
	"strings"
)

func main() {
	root := "e:/PHOTO"
	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if path == root {
			return nil
		}

		fileName := filepath.Base(path)
		if !strings.HasSuffix(fileName, ".jpg") {
			return nil
		}

		f, err := os.Open(path)
		if err != nil {
			return nil
		}

		//fmt.Printf("%s\n", path)
		_, err = readExifInfo(fileName, f)
		if err != nil {
			println(path)
			return nil
		}

		//timestamp := eInfo.Timestamp()
		//if timestamp == nil {
		//	println("get timestamp failed " + path)
		//	return nil
		//}

		return nil
	})

	if err != nil {
		println("walk error: " + err.Error())
	}
}

// ifdPath => tagName => exifInfo
type exifInfo struct {
	entries map[exif.IfdTag] exif.Entry
}

func NewExifInfo(entries map[exif.IfdTag] exif.Entry) *exifInfo {
	var info = &exifInfo{
		entries: entries,
	}

	return info
}

//
//// 获取 经度、纬度、高度 如果没有数据应返回 error
//func (m *exifInfo) GetLocationInfo() (*dbmodel.ExifGpsInfo, error) {
//	var out = dbmodel.ExifGpsInfo{
//		DateTime: m.MustGetGpsDateTime(),
//	}
//
//	latitude, err := m.getLocationValue("GPSLatitudeRef", "GPSLatitude")
//	if err != nil {
//		return nil, errors.Wrap(err, "get latitude failed")
//	}
//	longitude, err := m.getLocationValue("GPSLongitudeRef", "GPSLongitude")
//	if err != nil {
//		return nil, errors.Wrap(err, "get longitude failed")
//	}
//
//	out.Latitude = latitude
//	out.Longitude = longitude
//
//	// 高度缺 置为 0
//	out.Altitude = m.MustGetAltitude()
//	return &out, nil
//}

func readExifInfo(name string, r io.Reader) (*dbmodel.PictureExifInfo, error) {
	exifReader := exif.New()

	_, err := io.Copy(exifReader, r)
	if err == nil {
		return nil, errors.New("exif empty?")
	}
	if err != nil && err != exif.ErrFoundExifInData {
		return nil, errors.Wrap(err, "cannot found exif data")
	}
	err = exifReader.Parse()
	if err != nil {
		return nil, errors.Wrap(err, "parse exif failed")
	}

	//var info = NewExifInfo(exifReader.Raw)
	//println(info)
	
	//var shotInfo = &dbmodel.ExifShotInfo{
	//	ExposureTime: info.MustGetExposureTime(),
	//	FNumber: info.MustGetFNumber(),
	//	IsoSpeed: info.MustGetIsoSpeed(),
	//	FocalLength: info.MustGetFocalLength(),
	//	Flash: int(info.MustGetShort("IFD/Exif", "Flash")),
	//}
	//var devInfo = &dbmodel.ExifDeviceInfo{
	//	DateTime: info.MustGetDateTime(),
	//	Make: info.MustGetString("IFD", "Make"),
	//	CModel: info.MustGetString("IFD", "Model"),
	//}
	//var sizeInfo = &dbmodel.ExifSizeInfo{
	//	Orientation: int(info.MustGetShort("IFD", "Orientation")),
	//}

	var out = &dbmodel.PictureExifInfo{
		FileName:   name,
		//ShotInfo:   shotInfo,
		//DeviceInfo: devInfo,
		//SizeInfo:   sizeInfo,
	}

	//gpsInfo, err := info.GetLocationInfo()
	//if err == nil {
	//	out.GpsInfo = gpsInfo
	//}

	return out, nil
}
